<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入文章标题"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="板块选择" prop="classId">
        <el-select
          v-model="queryParams.classId"
          placeholder="请选择板块"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in articleClassList"
            :key="item.id"
            :label="item.className"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="获取状态" prop="searchType">
        <el-select
          v-model="queryParams.searchType"
          placeholder="请选择获取状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in searchTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList">
      <el-table-column label="文章ID" align="center" key="id" prop="id" v-if="columns[0].visible" />
      <el-table-column label="文章标题" align="center" key="title" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="用户ID" align="center" key="userId" prop="userId" v-if="columns[2].visible" />
      <el-table-column label="文章内容" align="center" key="content" prop="content" v-if="columns[3].visible" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[4].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" v-if="columns[5].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" v-if="columns[6].visible">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="handleSetTop(scope.row)"
          >置顶</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePaginationChange"
    />

    <!-- 文章详情弹窗 -->
    <el-dialog :title="'文章详情 - ' + (currentArticle.title || '')" :visible.sync="dialogVisible" width="90%" append-to-body>
      <div class="article-detail-layout">
        <!-- 左侧内容 -->
        <div class="article-left">
          <!-- 用户信息 -->
          <div class="user-info">
            <div class="user-avatar">
              <img :src="currentArticle.userAvatar || '/static/images/default-avatar.png'" alt="用户头像" />
            </div>
            <div class="user-details">
              <h4>{{ currentArticle.userName || '未知用户' }}</h4>
              <p>次元ID: {{ currentArticle.userId || '未知' }}</p>
            </div>
          </div>

          <!-- 文章内容 -->
          <div class="article-content">
            <h3>文章标题：{{ currentArticle.title }}</h3>
            <div class="content-html" v-html="currentArticle.content"></div>
          </div>

          <!-- 图片展示 -->
          <div class="media-section" v-if="currentArticle.imageList && currentArticle.imageList.length > 0">
            <h4>图片 ({{ currentArticle.imageList.length }}张)</h4>
            <div class="image-gallery">
              <el-image
                v-for="(image, index) in currentArticle.imageList"
                :key="index"
                :src="image.compressUrl || image.imageUrl"
                :preview-src-list="imageList"
                :initial-index="index"
                fit="cover"
                class="image-item"
                style="width: 120px; height: 120px;"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
          </div>

          <!-- 视频展示 -->
          <div class="media-section" v-if="currentArticle.videoList && currentArticle.videoList.length > 0">
            <h4>视频 ({{ currentArticle.videoList.length }}个)</h4>
            <div class="video-gallery">
              <div 
                v-for="(video, index) in currentArticle.videoList" 
                :key="index" 
                class="video-item"
              >
                <video 
                  :src="video.imageUrl" 
                  :poster="video.compressUrl"
                  controls
                  preload="metadata"
                ></video>
              </div>
            </div>
          </div>

          <!-- 其他信息 -->
          <div class="article-meta">
            <div class="meta-item">
              <strong>发布时间：</strong>{{ parseTime(currentArticle.createTime) }}
            </div>
            <div class="meta-item" v-if="currentArticle.address">
              <strong>地址：</strong>{{ currentArticle.address }}
            </div>
            <div class="meta-item" v-if="currentArticle.tags && currentArticle.tags.length > 0">
              <strong>标签：</strong>
              <el-tag 
                v-for="tag in currentArticle.tags" 
                :key="tag.tagName" 
                size="small" 
                style="margin-right: 5px;"
              >
                {{ tag.tagName }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 右侧推荐设置 -->
        <div class="article-right">
          <div class="recommend-section">
            <h4>推荐设置</h4>
            <el-form :model="recommendForm" label-width="120px">
              <el-form-item label="推荐状态">
                <el-radio-group v-model="recommendForm.isRecommended">
                  <el-radio :label="true">推荐</el-radio>
                  <el-radio :label="false">未推荐</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveRecommend">保存推荐设置</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 置顶设置弹窗 -->
    <el-dialog title="设置置顶" :visible.sync="topDialogVisible" width="40%" append-to-body>
      <el-form :model="topForm" label-width="120px">
        <!-- <el-form-item label="选择板块" prop="promotionType">
          <el-select
            v-model="topForm.promotionType"
            placeholder="请选择板块"
            clearable
            style="width: 240px"
            disabled
          >
            <el-option
              v-for="item in articleClassList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="置顶结束时间" prop="endTime">
          <el-date-picker
            v-model="topForm.endTime"
            type="datetime"
            placeholder="选择置顶结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="topEndTimeOptions"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveTopSettings">确定</el-button>
        <el-button @click="topDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { listArticle, getArticleClassList, setTopArticle, setRecommendArticle } from "@/api/user/article";

export default {
  name: "Article",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 所有文章数据
      allArticleList: [],
      // 当前页显示的文章数据
      articleList: [],
      // 获取状态选项
      searchTypeOptions: [
        { value: "0", label: "默认" },
        { value: "1", label: "最新" },
        { value: "2", label: "最热" },
        { value: "3", label: "随机" }
      ],
      // 板块列表
      articleClassList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        userId: undefined,
        searchType: "3",
        classId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `文章ID`, visible: true },
        { key: 1, label: `文章标题`, visible: true },
        { key: 2, label: `用户ID`, visible: true },
        { key: 3, label: `文章内容`, visible: true },
        { key: 4, label: `创建时间`, visible: true },
        { key: 5, label: `更新时间`, visible: true },
        { key: 6, label: `操作`, visible: true }
      ],
      // 弹窗相关
      dialogVisible: false,
      topDialogVisible: false,
      currentArticle: {},
      // 推荐表单
      recommendForm: {
        isRecommended: false
      },
      // 置顶表单
      topForm: {
        // promotionType: undefined,
        endTime: ''
      }

    };
  },
  created() {
      this.getArticleClassList().then(() => {
        this.getList();
      });
    },
    watch: {
  },
  computed: {
    /** 图片列表 */
    imageList() {
      if (!this.currentArticle.imageList) return [];
      return this.currentArticle.imageList.map(image => image.imageUrl);
    },

    /** 置顶结束时间选择器选项 */
    topEndTimeOptions() {
        const today = new Date();
        const sevenDaysLater = new Date();
        sevenDaysLater.setDate(today.getDate() + 7);
        
        return {
          disabledDate: (time) => {
            // 不能选择今天之前的日期，也不能选择7天后的日期
            return time.getTime() < today.getTime() - 8.64e7 || 
                   time.getTime() > sevenDaysLater.getTime();
          }
        };
      }
  },
  methods: {
    /** 获取板块列表 */
    getArticleClassList() {
      return getArticleClassList().then(response => {
        this.articleClassList = response.rows || response.data || [];
        // 如果列表不为空，默认选中第一个元素
        if (this.articleClassList.length > 0 && this.queryParams.classId === undefined) {
          this.queryParams.classId = this.articleClassList[0].id;
        }
      }).catch(error => {
        this.$modal.msgError('获取板块列表失败');
        console.error('获取板块列表失败:', error);
        return Promise.reject(error);
      });
    },
    /** 查询文章列表 */
    getList() {
      this.loading = true;
      // 请求所有数据，不分页
      const params = {
        title: this.queryParams.title,
        userId: this.queryParams.userId,
        searchType: this.queryParams.searchType,
        classIds: this.queryParams.classId,
        pageNum: 1,
        pageSize: 10// 请求大量数据
      };
      
      listArticle(params).then(response => {
        this.allArticleList = response.rows || [];
        this.total = this.allArticleList.length;
        this.updateCurrentPageData();
        this.loading = false;
      });
    },
    
    /** 更新当前页数据 */
    updateCurrentPageData() {
      const startIndex = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const endIndex = startIndex + this.queryParams.pageSize;
      this.articleList = this.allArticleList.slice(startIndex, endIndex);
    },
    
    /** 分页变化处理 */
    handlePaginationChange(pagination) {
      this.queryParams.pageNum = pagination.page;
      this.queryParams.pageSize = pagination.limit;
      this.updateCurrentPageData();
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.searchType = "3";
      this.queryParams.classId = undefined;
      this.handleQuery();
    },
    
    /** 查看文章详情 */
    handleView(row) {
      this.currentArticle = { ...row };
      this.dialogVisible = true;
      // 初始化推荐表单
      this.recommendForm = {
        isRecommended: row.isRecommended || false
      };
    },
    
    /** 处理置顶设置 */
    handleSetTop(row) {
      this.currentArticle = { ...row };
      this.topDialogVisible = true;
      // 初始化置顶表单，默认选择第一个板块和7天后的日期
      this.topForm = {
        endTime: ''
      };
      
      // 如果板块列表不为空且没有选择时间，默认设置为7天后（包含时分秒）
      if (this.articleClassList.length > 0 && !this.topForm.endTime) {
        const sevenDaysLater = new Date();
        sevenDaysLater.setDate(new Date().getDate() + 7);
        // 格式化日期时间为 yyyy-MM-dd HH:mm:ss
        const year = sevenDaysLater.getFullYear();
        const month = String(sevenDaysLater.getMonth() + 1).padStart(2, '0');
        const day = String(sevenDaysLater.getDate()).padStart(2, '0');
        const hours = String(sevenDaysLater.getHours()).padStart(2, '0');
        const minutes = String(sevenDaysLater.getMinutes()).padStart(2, '0');
        const seconds = String(sevenDaysLater.getSeconds()).padStart(2, '0');
        this.topForm.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
    },
    
    /** 保存置顶设置 */
    saveTopSettings() {
      // Ensure articleId is properly formatted as a number
      const articleId = Number(this.currentArticle.id);
      
      // 验证表单
      if (!this.topForm.endTime) {
        this.$modal.msgError('请选择置顶结束时间');
        return;
      }
      
      // Get promotionType - prioritize from classIds, then from articleClassList
      let promotionType = null;
      if (this.currentArticle.classIds && this.currentArticle.classIds.length > 0) {
        promotionType = this.currentArticle.classIds[0];
      } else if (this.articleClassList && this.articleClassList.length > 0) {
        promotionType = this.articleClassList[0].id;
      }
      
      // Validate required parameters
      if (!articleId && articleId !== 0) {
        this.$modal.msgError('文章ID不能为空');
        return;
      }
      if (!promotionType) {
        this.$modal.msgError('无法获取板块信息，请先选择板块');
        return;
      }
      
      // Create request data with explicit property names to ensure proper parameter mapping
      const requestData = {
        articleId: articleId,
        promotionType: promotionType,
        endTime: String(this.topForm.endTime)
      };
      
      console.log('Request data being sent:', requestData);
      
      // 调用置顶接口
      setTopArticle(requestData).then(() => {
        this.$modal.msgSuccess('置顶设置成功');
        this.topDialogVisible = false;
        // 刷新列表
        this.getList();
      }).catch(error => {
        this.$modal.msgError('置顶设置失败');
        console.error('置顶设置失败:', error);
      });
    },
    

    
    /** 保存推荐设置 */
    saveRecommend() {
      // 验证表单
      if (!this.currentArticle.id) {
        this.$modal.msgError("文章ID不能为空");
        return;
      }
      
      // 调用推荐设置的接口
      setRecommendArticle(this.currentArticle.id).then(() => {
        this.$modal.msgSuccess("推荐设置成功");
        this.dialogVisible = false;
      }).catch(error => {
        this.$modal.msgError("推荐设置失败：" + (error.message || '未知错误'));
      });
    }
  }
};
</script>

<style scoped>
.article-detail-layout {
  display: flex;
  gap: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.article-left {
  flex: 1;
  overflow-y: auto;
}

.article-right {
  width: 350px;
  flex-shrink: 0;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.user-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
}

.user-details h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.user-details p {
  margin: 0;
  color: #666;
}

.article-content {
  margin-bottom: 20px;
}

.article-content h3 {
  color: #333;
  margin-bottom: 10px;
}

.content-html {
  line-height: 1.6;
  color: #333;
}

.media-section {
  margin-bottom: 20px;
}

.media-section h4 {
  color: #333;
  margin-bottom: 10px;
}

.image-gallery, .video-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.2s;
}

.image-item:hover {
  transform: scale(1.05);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.video-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.video-item video {
  width: 200px;
  height: 150px;
  object-fit: cover;
}

.article-meta {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.meta-item {
  margin-bottom: 10px;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.recommend-section {
  padding: 15px;
  background-color: #f0f8ff;
  border-radius: 8px;
  position: sticky;
  top: 0;
}

.recommend-section h4 {
  margin-top: 0;
  color: #333;
}


</style>
